package com.ash.tx.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.ash.tx.bean.User;
import com.ash.tx.dao.UserDao;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public User queryUser(Long userId) {
        String sql = "select * from user where id=?";

        User queryForObject = jdbcTemplate.queryForObject(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User user = new User();

                user.setId(rs.getLong("id"));
                user.setName(rs.getString("name"));
                user.setAge(rs.getInt("age"));
                user.setBalance(rs.getDouble("balance"));
                user.setAddress(rs.getString("address"));

                return user;
            }
        }, userId);

        return queryForObject;
    }

    public void updateUser(User user) {
        String sql = "update user set name=?,age=?,address=?, balance=? where id=?";

        jdbcTemplate.update(sql, user.getName(), user.getAge(), user.getAddress(), user.getBalance(), user.getId());
    }

}
